import { Consultation, FollowUpTask, PatientRiskStratification, InterventionPlan } from '../models/Doctor';
import { PatientProfile } from '../models/User';
import { RiskPrediction } from '../models/Prediction';
import { Storage } from '@kit.StorageKit';
import { UserService } from './UserService';
import { PredictionService } from './PredictionService';

// 医生服务类
export class DoctorService {
  private static instance: DoctorService;
  private consultationKeyPrefix = 'consultation_';
  private followUpKeyPrefix = 'followup_';
  private riskStratKeyPrefix = 'riskstrat_';
  private interventionKeyPrefix = 'intervention_';
  private userService: UserService;
  private predictionService: PredictionService;

  // 单例模式
  public static getInstance(): DoctorService {
    if (!DoctorService.instance) {
      DoctorService.instance = new DoctorService();
    }
    return DoctorService.instance;
  }

  constructor() {
    this.userService = UserService.getInstance();
    this.predictionService = PredictionService.getInstance();
  }

  // 创建远程会诊
  async createConsultation(consultation: Omit<Consultation, 'id' | 'status'>): Promise<Consultation | null> {
    try {
      const newConsultation: Consultation = {
        ...consultation,
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        status: 'scheduled'
      };

      // 保存会诊记录
      await Storage.setOrCreate(this.consultationKeyPrefix + newConsultation.id, JSON.stringify(newConsultation));

      // 保存医生的会诊列表
      await this.addConsultationToDoctor(newConsultation.doctorId, newConsultation.id);

      // 保存患者的会诊列表
      await this.addConsultationToPatient(newConsultation.patientId, newConsultation.id);

      return newConsultation;
    } catch (error) {
      console.error('创建远程会诊失败:', error);
      return null;
    }
  }

  // 获取会诊详情
  async getConsultation(consultationId: string): Promise<Consultation | null> {
    try {
      const data = await Storage.get(this.consultationKeyPrefix + consultationId);
      return data ? JSON.parse(data) : null;
    } catch (error) {
      console.error('获取会诊详情失败:', error);
      return null;
    }
  }

  // 更新会诊状态
  async updateConsultationStatus(consultationId: string, status: Consultation['status']): Promise<boolean> {
    try {
      const consultation = await this.getConsultation(consultationId);
      if (!consultation) {
        return false;
      }

      consultation.status = status;
      
      // 如果会诊完成，记录结束时间和持续时间
      if (status === 'completed') {
        consultation.endTime = new Date();
        if (consultation.startTime) {
          consultation.duration = Math.round((new Date(consultation.endTime).getTime() - new Date(consultation.startTime).getTime()) / (1000 * 60));
        }
      }

      await Storage.setOrCreate(this.consultationKeyPrefix + consultationId, JSON.stringify(consultation));
      return true;
    } catch (error) {
      console.error('更新会诊状态失败:', error);
      return false;
    }
  }

  // 添加会诊记录
  async addConsultationNotes(consultationId: string, notes: string, diagnosis?: string, prescription?: string): Promise<boolean> {
    try {
      const consultation = await this.getConsultation(consultationId);
      if (!consultation) {
        return false;
      }

      consultation.notes = notes;
      if (diagnosis) consultation.diagnosis = diagnosis;
      if (prescription) consultation.prescription = prescription;

      await Storage.setOrCreate(this.consultationKeyPrefix + consultationId, JSON.stringify(consultation));
      return true;
    } catch (error) {
      console.error('添加会诊记录失败:', error);
      return false;
    }
  }

  // 获取医生的会诊列表
  async getDoctorConsultations(doctorId: string, status?: string): Promise<Consultation[]> {
    try {
      const consultationIdsData = await Storage.get(this.consultationKeyPrefix + 'doctor_' + doctorId);
      if (!consultationIdsData) {
        return [];
      }

      const consultationIds: string[] = JSON.parse(consultationIdsData);
      const consultations: Consultation[] = [];

      for (const id of consultationIds) {
        const consultation = await this.getConsultation(id);
        if (consultation) {
          if (!status || consultation.status === status) {
            consultations.push(consultation);
          }
        }
      }

      // 按时间排序（最近的在前）
      return consultations.sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime());
    } catch (error) {
      console.error('获取医生会诊列表失败:', error);
      return [];
    }
  }

  // 获取患者的会诊列表
  async getPatientConsultations(patientId: string): Promise<Consultation[]> {
    try {
      const consultationIdsData = await Storage.get(this.consultationKeyPrefix + 'patient_' + patientId);
      if (!consultationIdsData) {
        return [];
      }

      const consultationIds: string[] = JSON.parse(consultationIdsData);
      const consultations: Consultation[] = [];

      for (const id of consultationIds) {
        const consultation = await this.getConsultation(id);
        if (consultation) {
          consultations.push(consultation);
        }
      }

      // 按时间排序（最近的在前）
      return consultations.sort((a, b) => new Date(b.startTime).getTime() - new Date(a.startTime).getTime());
    } catch (error) {
      console.error('获取患者会诊列表失败:', error);
      return [];
    }
  }

  // 创建随访任务
  async createFollowUpTask(task: Omit<FollowUpTask, 'id' | 'status' | 'reminderSent'>): Promise<FollowUpTask | null> {
    try {
      const newTask: FollowUpTask = {
        ...task,
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        status: 'pending',
        reminderSent: false
      };

      // 保存随访任务
      await Storage.setOrCreate(this.followUpKeyPrefix + newTask.id, JSON.stringify(newTask));

      // 保存医生的随访任务列表
      await this.addFollowUpTaskToDoctor(newTask.doctorId, newTask.id);

      // 保存患者的随访任务列表
      await this.addFollowUpTaskToPatient(newTask.patientId, newTask.id);

      return newTask;
    } catch (error) {
      console.error('创建随访任务失败:', error);
      return null;
    }
  }

  // 获取随访任务
  async getFollowUpTask(taskId: string): Promise<FollowUpTask | null> {
    try {
      const data = await Storage.get(this.followUpKeyPrefix + taskId);
      return data ? JSON.parse(data) : null;
    } catch (error) {
      console.error('获取随访任务失败:', error);
      return null;
    }
  }

  // 更新随访任务状态
  async updateFollowUpTaskStatus(taskId: string, status: FollowUpTask['status'], notes?: string): Promise<boolean> {
    try {
      const task = await this.getFollowUpTask(taskId);
      if (!task) {
        return false;
      }

      task.status = status;
      if (notes) task.notes = notes;
      
      // 如果完成随访，记录完成时间
      if (status === 'completed') {
        task.completedDate = new Date();
      }

      await Storage.setOrCreate(this.followUpKeyPrefix + taskId, JSON.stringify(task));
      return true;
    } catch (error) {
      console.error('更新随访任务状态失败:', error);
      return false;
    }
  }

  // 发送随访提醒
  async sendFollowUpReminder(taskId: string): Promise<boolean> {
    try {
      const task = await this.getFollowUpTask(taskId);
      if (!task) {
        return false;
      }

      // 标记提醒已发送
      task.reminderSent = true;
      await Storage.setOrCreate(this.followUpKeyPrefix + taskId, JSON.stringify(task));

      // 这里应该集成实际的提醒发送逻辑
      console.log('发送随访提醒:', task.title, task.scheduledDate);

      return true;
    } catch (error) {
      console.error('发送随访提醒失败:', error);
      return false;
    }
  }

  // 获取医生的随访任务列表
  async getDoctorFollowUpTasks(doctorId: string, status?: string): Promise<FollowUpTask[]> {
    try {
      const taskIdsData = await Storage.get(this.followUpKeyPrefix + 'doctor_' + doctorId);
      if (!taskIdsData) {
        return [];
      }

      const taskIds: string[] = JSON.parse(taskIdsData);
      const tasks: FollowUpTask[] = [];

      for (const id of taskIds) {
        const task = await this.getFollowUpTask(id);
        if (task) {
          if (!status || task.status === status) {
            tasks.push(task);
          }
        }
      }

      // 按计划日期排序
      return tasks.sort((a, b) => new Date(a.scheduledDate).getTime() - new Date(b.scheduledDate).getTime());
    } catch (error) {
      console.error('获取医生随访任务列表失败:', error);
      return [];
    }
  }

  // 获取患者的随访任务列表
  async getPatientFollowUpTasks(patientId: string): Promise<FollowUpTask[]> {
    try {
      const taskIdsData = await Storage.get(this.followUpKeyPrefix + 'patient_' + patientId);
      if (!taskIdsData) {
        return [];
      }

      const taskIds: string[] = JSON.parse(taskIdsData);
      const tasks: FollowUpTask[] = [];

      for (const id of taskIds) {
        const task = await this.getFollowUpTask(id);
        if (task) {
          tasks.push(task);
        }
      }

      // 按计划日期排序
      return tasks.sort((a, b) => new Date(a.scheduledDate).getTime() - new Date(b.scheduledDate).getTime());
    } catch (error) {
      console.error('获取患者随访任务列表失败:', error);
      return [];
    }
  }

  // 创建患者风险分层
  async createRiskStratification(patientId: string, riskFactors: any[], overallRisk: string): Promise<PatientRiskStratification | null> {
    try {
      const newStratification: PatientRiskStratification = {
        patientId,
        overallRisk: overallRisk as any,
        riskFactors,
        assessmentDate: new Date(),
        nextAssessmentDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) // 30天后
      };

      // 保存风险分层
      await Storage.setOrCreate(this.riskStratKeyPrefix + patientId, JSON.stringify(newStratification));

      return newStratification;
    } catch (error) {
      console.error('创建患者风险分层失败:', error);
      return null;
    }
  }

  // 获取患者风险分层
  async getPatientRiskStratification(patientId: string): Promise<PatientRiskStratification | null> {
    try {
      const data = await Storage.get(this.riskStratKeyPrefix + patientId);
      return data ? JSON.parse(data) : null;
    } catch (error) {
      console.error('获取患者风险分层失败:', error);
      return null;
    }
  }

  // 更新患者风险分层
  async updateRiskStratification(patientId: string, riskFactors: any[], overallRisk: string): Promise<boolean> {
    try {
      const stratification = await this.getPatientRiskStratification(patientId);
      if (!stratification) {
        return false;
      }

      stratification.riskFactors = riskFactors;
      stratification.overallRisk = overallRisk as any;
      stratification.assessmentDate = new Date();
      stratification.nextAssessmentDate = new Date(Date.now() + 30 * 24 * 60 * 60 * 1000); // 30天后

      await Storage.setOrCreate(this.riskStratKeyPrefix + patientId, JSON.stringify(stratification));
      return true;
    } catch (error) {
      console.error('更新患者风险分层失败:', error);
      return false;
    }
  }

  // 创建干预计划
  async createInterventionPlan(plan: Omit<InterventionPlan, 'id' | 'createdAt' | 'updatedAt'>): Promise<InterventionPlan | null> {
    try {
      const newPlan: InterventionPlan = {
        ...plan,
        id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
        createdAt: new Date(),
        updatedAt: new Date()
      };

      // 保存干预计划
      await Storage.setOrCreate(this.interventionKeyPrefix + newPlan.id, JSON.stringify(newPlan));

      // 更新患者风险分层中的干预计划
      const stratification = await this.getPatientRiskStratification(newPlan.patientId);
      if (stratification) {
        stratification.interventionPlan = newPlan;
        await Storage.setOrCreate(this.riskStratKeyPrefix + newPlan.patientId, JSON.stringify(stratification));
      }

      return newPlan;
    } catch (error) {
      console.error('创建干预计划失败:', error);
      return null;
    }
  }

  // 获取干预计划
  async getInterventionPlan(planId: string): Promise<InterventionPlan | null> {
    try {
      const data = await Storage.get(this.interventionKeyPrefix + planId);
      return data ? JSON.parse(data) : null;
    } catch (error) {
      console.error('获取干预计划失败:', error);
      return null;
    }
  }

  // 更新干预计划
  async updateInterventionPlan(planId: string, updates: Partial<InterventionPlan>): Promise<boolean> {
    try {
      const plan = await this.getInterventionPlan(planId);
      if (!plan) {
        return false;
      }

      const updatedPlan = {
        ...plan,
        ...updates,
        updatedAt: new Date()
      };

      await Storage.setOrCreate(this.interventionKeyPrefix + planId, JSON.stringify(updatedPlan));
      return true;
    } catch (error) {
      console.error('更新干预计划失败:', error);
      return false;
    }
  }

  // 获取高风险患者列表
  async getHighRiskPatients(doctorId: string): Promise<PatientProfile[]> {
    try {
      // 获取医生的所有患者
      const patients = await this.userService.getPatientsByDoctor(doctorId);
      const highRiskPatients: PatientProfile[] = [];

      for (const patient of patients) {
        const riskStratification = await this.getPatientRiskStratification(patient.id);
        // 如果风险分层为高风险或关键风险，添加到列表
        if (riskStratification && (riskStratification.overallRisk === 'high' || riskStratification.overallRisk === 'critical')) {
          highRiskPatients.push(patient);
        }
      }

      return highRiskPatients;
    } catch (error) {
      console.error('获取高风险患者列表失败:', error);
      return [];
    }
  }

  // 生成患者健康报告
  async generatePatientHealthReport(patientId: string): Promise<any> {
    try {
      // 获取患者信息
      const patient = await this.userService.getUserProfile(patientId) as PatientProfile;
      if (!patient) {
        throw new Error('患者不存在');
      }

      // 获取风险预测
      const predictions = await this.predictionService.predictRisk(patientId, patient);

      // 获取风险分层
      const riskStratification = await this.getPatientRiskStratification(patientId);

      // 生成报告
      const report = {
        patientInfo: {
          name: patient.realName,
          age: patient.age,
          gender: patient.gender,
          diseases: patient.diseases
        },
        riskAssessment: {
          currentRisk: riskStratification?.overallRisk || 'unknown',
          riskFactors: riskStratification?.riskFactors || [],
          predictions
        },
        interventionPlan: riskStratification?.interventionPlan,
        generatedDate: new Date()
      };

      return report;
    } catch (error) {
      console.error('生成患者健康报告失败:', error);
      return null;
    }
  }

  // 辅助方法：添加会诊到医生
  private async addConsultationToDoctor(doctorId: string, consultationId: string): Promise<void> {
    const doctorConsultationsData = await Storage.get(this.consultationKeyPrefix + 'doctor_' + doctorId);
    const doctorConsultations: string[] = doctorConsultationsData ? JSON.parse(doctorConsultationsData) : [];
    doctorConsultations.push(consultationId);
    await Storage.setOrCreate(this.consultationKeyPrefix + 'doctor_' + doctorId, JSON.stringify(doctorConsultations));
  }

  // 辅助方法：添加会诊到患者
  private async addConsultationToPatient(patientId: string, consultationId: string): Promise<void> {
    const patientConsultationsData = await Storage.get(this.consultationKeyPrefix + 'patient_' + patientId);
    const patientConsultations: string[] = patientConsultationsData ? JSON.parse(patientConsultationsData) : [];
    patientConsultations.push(consultationId);
    await Storage.setOrCreate(this.consultationKeyPrefix + 'patient_' + patientId, JSON.stringify(patientConsultations));
  }

  // 辅助方法：添加随访任务到医生
  private async addFollowUpTaskToDoctor(doctorId: string, taskId: string): Promise<void> {
    const doctorTasksData = await Storage.get(this.followUpKeyPrefix + 'doctor_' + doctorId);
    const doctorTasks: string[] = doctorTasksData ? JSON.parse(doctorTasksData) : [];
    doctorTasks.push(taskId);
    await Storage.setOrCreate(this.followUpKeyPrefix + 'doctor_' + doctorId, JSON.stringify(doctorTasks));
  }

  // 辅助方法：添加随访任务到患者
  private async addFollowUpTaskToPatient(patientId: string, taskId: string): Promise<void> {
    const patientTasksData = await Storage.get(this.followUpKeyPrefix + 'patient_' + patientId);
    const patientTasks: string[] = patientTasksData ? JSON.parse(patientTasksData) : [];
    patientTasks.push(taskId);
    await Storage.setOrCreate(this.followUpKeyPrefix + 'patient_' + patientId, JSON.stringify(patientTasks));
  }
}